<?php

/**
 * 
 */

class InstallApi extends ApiBase{


	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();
	}
	
	public function check(){
		if(defined("N_INSTALLED") && 'Y'==N_INSTALLED){
			return true;
		}
		if('install'!=N_EVENT){
			n_go(n_url("install","index"));
		}
	}
	public function islogin(){
		if(!isset($_SESSION['islogin']) || 'Y'!=$_SESSION['islogin']){
			n_go(n_url("install","login"));
		}
		
	}
	/**
	 * 判断系统是否正确安装需要确定
	 * 1.插件管理账号是否成功建立
	 * 2.内核配置文件是否存在
	 */
	public function isInstall(){
		$conf = n_confGet("install");
		
		if(!$conf['state']){
			n_go(n_url("install","init"));
		}

		$conf = n_confGet("_core");
		
		if(!$conf['state']){
			n_go(n_url("install","initStep2"));
		}

	}
	

	public function curlGet($url,$port=0,$host='', $timeout = 10,$proxy=''){
		
		$rs = n_state(TRUE, "请求成功");
		$ch = curl_init();
		$options = array(
						CURLOPT_URL => $url,
						CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
						CURLOPT_RETURNTRANSFER => 1,
						CURLOPT_BINARYTRANSFER => 1,     
						CURLOPT_TIMEOUT		   => $timeout,
					);
		curl_setopt_array($ch, $options);
					
		if(!empty($port)){
			curl_setopt($ch, CURLOPT_PORT, $port);
		}
		
		if(!empty($host)){
			curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: {$host}"));
		}
		if(!empty($proxy) && preg_match("/^\\d{1,3}(\\.\\d{1,3}){3}:\\d{1,5}$/",$proxy)){
			curl_setopt($ch, CURLOPT_PROXY, $proxy);
		}
		
		$respond = curl_exec($ch);
		$curlRs = curl_getinfo($ch);		
		curl_close($ch);
		$rs['header'] = $curlRs;
		$rs['respond'] = $respond;
		
		return $rs;	
	}

	private function pluginState($pcode,$state){
		
		try{
			if(!in_array($state, array('start','stop','remove'))){
				throw new PException("状态只允许:start,stop,remove");
			}
			$pconf = n_confGet("_plugins");
			if(!$pconf['state']){
				throw new PException("获取配置文件失败");
			}
			if(!isset($pconf['data'][$pcode])){
				throw new PException("找不到插件{$pcode}的配置");
			}
			$pconf['data'][$pcode]['state'] = $state;
			n_confSave("_plugins", $pconf['data']);
			$rs = n_state(TRUE, "停止成功");
		}catch(PException $p){
			$rs = n_state(FALSE, $p->getMessage());
		}
		return $rs;
		
	}
	public function pluginStop($pcode){
		return $this->pluginState($pcode,'stop');
	}


	public function pluginStart($pcode){
		return $this->pluginState($pcode,'start');		
	}

	public function pluginRemove($pcode){
		return $this->pluginState($pcode,'remove');		
	}

	/**
	 * 可以设定超时时间，如果超时再次抓取次数
	 */
	public function download($url,$dir,$host=''){
		
		$header['http'] = array('timeout' => 10);
		if(!empty($host)){
			$header['http']['header'] = "Host: m3.sohu.com";
		}
		$scc = stream_context_create($header);
		//print_r($header);
		$data = file_get_contents($url,1,$scc);


		//echo $dir;
		if(is_bool($data)){
			return n_state(FALSE, "下载失败0！");
		}
		if(!is_dir(dirname($dir))){
			mkdir(dirname($dir));
		}

		file_put_contents($dir, $data);
		return n_state(TRUE, "下载成功1");
	}

	public function getPlugins(){
		$param = $this->param("pcode:char");
		if(empty($param['pcode'])){
			throw new PException("参数错误");
		}
		
		$url = "http://10.10.126.109/open/pbox/getPlugins.html?pcode={$param['pcode']}";
		$rs = $this->curlGet($url,0,'m2.sohu.com');
		//print_r($rs);
		return $rs['respond'];
	}
	public function getList(){
		//最新插件
		//推荐插件
		$param = $this->param("orb:char,page:page");
		$url = "http://10.10.126.109/open/pbox/getPlugins.html?pcode={$param['pcode']}";
		$rs = $this->curlGet($url,0,'m2.sohu.com');
		return $rs['respond'];
		
	}
	
	public function getListByTags($tag,$page=1){
		$url = "http://10.10.126.109/open/pbox/getListByTags.html?scode=cms&sign=e";
		//echo $url;
		$rs = $this->curlGet($url,0,'m3.sohu.com');
		//print_r($rs);
		return json_decode($rs['respond'],true);
		
	}
	
	
	/**
	 * 检查操作系统
	 */
	public function checkOs($os){
		if(empty($os)){
			$rs = n_state(TRUE,"操作系统:未定义需求");
		}else{
			
			if(!in_array(N_OS,array('win','linux'))){
				$rs = n_state(FALSE,"操作系统:配置规则错误");
			}else{
				if(N_OS!=$os){
					$rs = n_state(FALSE,"操作系统:需要{$os}");
				}else{
					$rs = n_state(TRUE, "操作系统:符合需求");
				}
			}
		}
		return $rs;
	}
	
	/**
	 * 检查php版本是否符合要求
	 */
	public function checkPhpv($phplv){
		if(empty($phplv)){
			$rs = n_state(TRUE,'PHP版本:未定义需求');
		}else{
			
			$phpV = phpversion();//substr(phpversion(),0,strpos(phpversion(), '-'));
			//echo $phpV.'===';
			//echo strnatcmp(5, 5);
			if(strnatcmp($phpV, $phplv)<=0){
				$rs = n_state(FALSE,"当前版本{$phpV}低于{$phplv}");
			}else{
				$rs = n_state(TRUE,"PHP:当前版本{$phpV},满足要求最低要求{$phplv}");
			}
 
		}
		return $rs;
	}
	
	/**
	 * 检查插件依赖关系
	 */
	public function checkNexus($nexus='',$localcheck='N'){
		$rs = n_state(TRUE,"关系插件:未定义需求");
		if(!empty($nexus)){

			$pluginsConf = n_confGet("_plugins");
			$nexusArr = explode(",",$nexus);
			$rsMsg = '插件需求:';
			foreach($nexusArr as $key=>$val){
				preg_match("/^([a-z]*)\\[([dscp]+)([<=>]*)([0-9.]*)\\]([a-z]*)$/",$val,$match);
				if(count($match)!=6){
					$rs['state'] = FALSE;
					$rsMsg .= '关系规则错误';
					continue;
				}
				//print_r($match);
				switch($match[2]){
					case 'd':
						$rsMsg .= "依赖插件{$match['5']};";
						if('Y'==$localcheck){
							if(isset($pluginsConf['data'][$match[5]])){
								switch($pluginsConf['data'][$match[5]]['state']){
									case 'start':
											$rsMsg .= "插件{$match[5]}正常服务";
											break;
									case 'stop':
											$rsMsg .= "插件{$match[5]}停止服务";
											$rs['state'] = FALSE;
											$rsMsg .= n_href(n_url("install",'installed'),"开启插件{$match[5]}服务","target='_blank'");
											break;
									case 'remove':
											$rsMsg .= "插件{$match[5]}已移除服务";
											$rs['state'] = FALSE;
											$rsMsg .= n_href(n_url("install",'pluginInit',array("pcode"=>$match[5])),"安装插件{$match[5]}","target='_blank'");
											break;
									default:
											$rsMsg .= "插件{$match[5]}异常";
											$rs['state'] = FALSE;
								}
							}else{
								$rsMsg .= "插件未安装;";
								$rs['state'] = FALSE;
								$rsMsg .= n_href(n_url("install",'pluginInit',array("pcode"=>$match[5])),"安装插件{$match[5]}","target='_blank'");
		
							}
						}

						break;
					case 's':
						$rsMsg .= "建议插件{$match['5']};";
						if('Y'==$localcheck){
							if(isset($pluginsConf['data'][$match[5]])){
								switch($pluginsConf['data'][$match[5]]['state']){
									case 'start':
											$rsMsg .= "插件{$match[5]}正常服务";
											break;
									case 'stop':
											$rsMsg .= "插件{$match[5]}停止服务";
											$rsMsg .= n_href(n_url("install",'installed'),"开启插件{$match[5]}服务","target='_blank'");
											break;
									case 'remove':
											$rsMsg .= "插件{$match[5]}已移除服务";
											$rsMsg .= n_href(n_url("install",'pluginInit',array("pcode"=>$match[5])),"安装插件{$match[5]}","target='_blank'");
											break;
									default:
											$rsMsg .= "插件{$match[5]}异常";
								}
							}else{
								$rsMsg .= "插件未安装;";
								$rsMsg .= n_href(n_url("install",'pluginInit',array("pcode"=>$match[5])),"安装插件{$match[5]}","target='_blank'");
							}


						}
						break;
					case 'c':
						$rsMsg .= "冲突插件{$match['5']};";
						if('Y'==$localcheck){
							if(isset($pluginsConf['data'][$match[5]])){
								switch($pluginsConf['data'][$match[5]]['state']){
									case 'start':
											$rsMsg .= "插件{$match[5]}服务正在运行中";
											$rs['state'] = FALSE;
											$rsMsg .= n_href(n_url("install",'installed'),"停止或卸载插件{$match[5]}服务","target='_blank'");

											break;
									case 'stop':
											$rsMsg .= "插件{$match[5]}停止服务";
											break;
									case 'remove':
											$rsMsg .= "插件{$match[5]}已移除服务";
											break;
									default:
											$rsMsg .= "插件{$match[5]}异常";
								}
							}else{
								$rsMsg .= "插件未安装;";		
							}

						}
						break;
					case 'p':
						$rsMsg .= "囊括插件{$match['5']};";
						if('Y'==$localcheck){
						}
						break;
					default:
						$rsMsg .= "配置错误;".json_encode($match);
						$rs['state'] = FALSE;
						break;
				}
			}
			$rs['msg'] = $rsMsg;
		}
		return $rs;
	}
	
	/**
	 * 检查php扩展是否安装，这里仅仅实现对某个函数的判定来确定模块是否安装
	 * 
	 */
	public function checkExt($ext){
		try{
			if(empty($ext)){
				$rs = n_state(TRUE,'PHP扩展:未定义需求');
			}else{
				$extArr = explode(',',$ext);
				$rsMsg = "依赖扩展:";
				
				foreach($extArr as $key=>$val){
					$val = strtolower($val);
					$item = explode(':',$val);
					if(!in_array($item[0],array('F','C'))){
						throw new PException("扩展模块规则错误");
					}
					if('F'==$item[0]){
						$fc = function_exists($val);
					}else{
						$fc = class_exists($val);
					}
					$rsMsg .= $fc?"已定义{$val}":"未定义{$val}";
					
				}
				$rs = n_state(TRUE, $rsMsg);
			}
		}catch(PException $p){
			$rs = n_state(FALSE,$p->getMessage());
		}
		return $rs;
		
	}


}